package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import test.PerformanceAnalyze;

import java.util.concurrent.CountDownLatch;

public class TCPClient extends AbstractVerticle {

    PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();
    NetClient client;
    NetSocket socket;

    CountDownLatch countDownLatch = new CountDownLatch(1);

    public void send() throws InterruptedException {
        countDownLatch.await();

        socket.write(Buffer.buffer(Long.valueOf(System.nanoTime()).toString()+","));

        performanceAnalyze.meter();

//        // Handle the connection in here
//        socket.handler(buffer -> {
//            Arrays.stream(buffer.toString().split(",")).forEach(time -> {
//                try {
//                    Long nanoTime = Long.parseLong(time);
//                    performanceAnalyze.update((System.nanoTime() - nanoTime)/2);
//                } catch (Exception e) {
//
//                }
//            });
//
//            for (int i = 0; i < 100; i++) {
//                socket.write(Buffer.buffer(Long.valueOf(System.nanoTime()).toString()+","));
//            }
//        });
    }

    @Override
    public void start() throws Exception {
        String host = System.getProperty("publicAddress", "127.0.0.1");

        NetClientOptions options = new NetClientOptions();
        options.setTcpNoDelay(false);

        client = vertx.createNetClient(options);


        client.connect(1234, host, res -> {
            if (res.succeeded()) {
                System.out.println("Connected!");

                socket = res.result();

                for (int i = 0; i < 10000; i++) {
                    socket.write(Buffer.buffer(Long.valueOf(System.nanoTime()).toString()+","));
                }

                countDownLatch.countDown();
            } else {
                System.out.println("Failed to connect: " + res.cause().getMessage());
            }
        });

    }

    @Override
    public void stop() throws Exception {
        socket.close();
        client.close();
    }

    public static void main(String[] args) throws Exception {

    }
}
